<template>
	<view>
		<view class="uni-table send-table">
			<view class="flex align between">
				<view style="flex: 1;">
					<uni-search-bar cancelButton="none" placeholder="请用户名搜索" v-model="username" bgColor="#fff"
						@input="input" />
					</uni-section>
				</view>
				<view style="flex: 1;">
					<uni-search-bar cancelButton="none" placeholder="请昵称搜索" v-model="nickname" bgColor="#fff"
						@input="input" />
					</uni-section>
				</view>
			</view>

			<view class="flex align between" style="margin-bottom: 20rpx;">
				<view class="inputView2 flex between" style="width:58%;" @click="showTree()">
					<input v-model="orgin_text" placeholder="请选择所属党支部" disabled />
					<uni-icons type="down" size="18" color="#cecece"></uni-icons>
				</view>
				<view class="sendBtn sendBtn2" @click="toReLoad">重置</view>
				<view class="sendBtn" @click="toSend">发送消息</view>
			</view>
			<view class="flex align between" style="margin-bottom: 5rpx;">
				<view style="font-size: 24rpx;color: gray;margin-bottom: 5rpx;">共{{total}}人</view>
				<view style="font-size: 24rpx;margin-bottom: 5rpx;color: #55aaff;" v-if="selected.length!=0">
					已选：{{selected.length}}人</view>
			</view>
			<uni-table ref="table" :data="tableData" border stripe>
				<!--  type="selection" emptyText="暂无更多数据" @selection-change="selectionChange"-->
				<!-- 定义表头 -->
				<uni-tr>
					<uni-th>
						<checkbox :checked="checkAll" @click="all_change" />
					</uni-th>
					<uni-th width="160">昵称</uni-th>
					<uni-th width="160">党支部</uni-th>
					<uni-th width="40">用户名</uni-th>
				</uni-tr>
				<!-- 定义表格行数据 -->
				<!-- <view class="tableBody"> -->
				<uni-tr v-for="(item, index) in tableData" :key="index">
					<uni-td>
						<checkbox-group @change="handleChange(item.id.toString())">
							<checkbox :value="item.id.toString()" :checked="iselected(item.id)" />
						</checkbox-group>
					</uni-td>
					<uni-td>{{ item.nickname==null?'-':item.nickname }}</uni-td>
					<uni-td>{{ item.organization_text==null?'-':item.organization_text }}</uni-td>
					<uni-td>{{ item.username==null?'-':item.username }}</uni-td>
				</uni-tr>
				<!-- </view> -->
			</uni-table>
			<view style="margin-top: 20rpx;">
				<uni-pagination :current="current" :total="total" :pageSize="pageSize"
					@change="handlePageChange"></uni-pagination>
			</view>
		</view>
		<!-- 输入框示例 -->
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" title="发送消息" @confirm="dialogInputConfirm" :duration="2000"
				:before-close="true" @close="close">
				<view style="width: 100%;">
					<view class="inputView">
						<view class="view-tit">名称：</view>
						<view class="textarea">
							<u--textarea height="40" v-model="name" placeholder="请输入名称" count
								maxlength="20"></u--textarea>
						</view>
					</view>
					<view class="inputView">
						<view class="view-tit">通知内容：</view>
						<view class="textarea">
							<u--textarea height="40" v-model="content" placeholder="请输入内容" count
								maxlength="20"></u--textarea>
						</view>
					</view>
					<view class="inputView">
						<view class="view-tit">提示说明：</view>
						<view class="textarea">
							<u--textarea height="40" v-model="tip" placeholder="请输入提示说明" count
								maxlength="20"></u--textarea>
						</view>
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>
		<!-- 党支部 -->
		<peng-tree ref="pengTree" :range="itemsOrg" idKey="id" nameKey="name" allKey="arr" :multiple="false"
			:cascade="false" :selectParent="true" :foldAll="false" confirmColor="#007aff" cancelColor="#757575"
			title="请选择所属党支部" titleColor="#757575" @cancel="treeCancel" @confirm="treeConfirm">
		</peng-tree>
	</view>
</template>

<script>
	import {
		adminLists,
		sendMessageAdmin,
		organizationNewList
	} from '@/api/apiData.js';
	export default {
		data() {
			return {
				status: '',
				type: '',
				range1: [{
						value: 1,
						text: "流出"
					},
					{
						value: 2,
						text: "流入"
					},
				],
				range2: [{
						value: 1,
						text: "待审核"
					},
					{
						value: 2,
						text: "审核通过"
					},
					{
						value: 3,
						text: "审核未通过"
					},
					{
						value: 4,
						text: "已停用"
					},
					{
						value: 5,
						text: "已返乡"
					},
					{
						value: 6,
						text: "流动中"
					},
				],
				realname: '',
				current: 1, // 当前页码
				pageSize: 10, // 每页显示的数据条数
				total: 0, // 总数据条数，这里仅为示例，实际应从服务器获取
				tableData: [], // 表格数据，初始为空，后面根据分页加载数据
				selectedItem: '',
				selectedIndexs: [],
				content: '',
				tip: '',
				name: '',
				ids: '',
				selectedRows: [], // 用于存储被勾选行的信息
				idsArr: [],
				selected: [],
				checkAll: false,
				itemsOrg: [],
				organization: [],
				value: '',
				nickname: '',
				username: '',
				orgin_text: ''
			};
		},
		onLoad() {
			this.loadData();
			this.getOrg()
		},
		methods: {
			async getOrg() {
				const result = await organizationNewList()
				result.data.forEach(item => {
					item.arr = [item.id]
					if (item.children) {
						item.children.forEach(item2 => {
							item2.arr = [item.id, item2.id]
							if (item2.children) {
								item2.children.forEach(item3 => {
									item3.arr = [item.id, item2.id, item3.id]
									if (item3.children) {
										item3.children.forEach(item4 => {
											item4.arr = [item.id, item2.id, item3.id,
												item4.id
											]
										})
									}
								})
							}
						})
					}
				})
				this.itemsOrg = result.data
			},
			showTree() {
				//打开选择器
				this.$refs.pengTree._show();
				//关闭选择器
				//this.$refs.pengTree._hide();
			},
			treeCancel(e) {
				console.log("你点击了取消")
				console.log(e)
			},
			treeConfirm(e) {
				console.log("你点击了确定")
				console.log(e)
				this.orgin_text = e[0].name
				this.organization = e[0].value
				this.selected = []
				this.current = 1
				this.loadData()
			},
			onchangeOutOrg(e) {
				const value = e.detail.value
				console.log(value)
				let arr = []
				value.forEach(item => {
					arr.push(item.value)
				})
				this.organization = arr
			},
			toSend() {
				console.log(this.selected)
				// const uniqueArr = Array.from(new Set(this.idsArr.concat(this.selected)));
				// this.idsArr = uniqueArr
				if (this.selected.length == 0) {
					uni.showToast({
						title: '请选择人员',
						icon: 'error'
					})
					return false
				}
				this.$refs.inputDialog.open()
				console.log(this.selected)
				this.ids = this.selected.toString()
				// const uniqueArr = Array.from(new Set(this.idsArr.concat(this.selectedItems())));
				// this.idsArr = uniqueArr
				// console.log(uniqueArr); // [1, 2, 3, 4, 5]
				// if (this.idsArr.length == 0) {
				// 	uni.showToast({
				// 		title: '请选择人员',
				// 		icon: 'error'
				// 	})
				// 	return false
				// }
				// this.$refs.inputDialog.open()
				// this.ids = this.idsArr.toString()
				// console.log(this.ids)
			},
			async dialogInputConfirm() {
				console.log(this.ids)
				if (this.content == '') {
					uni.showToast({
						title: '请输入发送内容',
						icon: 'error'
					})
					return false
				}
				// console.log(this.content)
				// console.log(this.ids)
				const result = await sendMessageAdmin({
					content: this.content,
					name: this.name,
					tip: this.tip,
					id: this.ids
				})
				if (result.code == 1) {
					uni.showToast({
						title: result.msg,
					})
					this.$refs.inputDialog.close()
					setTimeout(() => {
						// this.$refs.table.clearSelection()
						this.selectedIndexs.length = 0
						this.loadData()
					}, 1000)
				} else {
					uni.showToast({
						title: result.msg,
						icon: 'error'
					})
				}
			},
			close() {
				this.$refs.inputDialog.close()
			},
			input(e) {
				// this.$refs.table.clearSelection()
				this.selected = []
				this.current = 1
				this.loadData()
			},
			// 多选处理
			selectedItems() {
				return this.selectedIndexs.map(i => this.tableData[i].id)
			},
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			change1(e) {
				// this.$refs.table.clearSelection()
				this.selected = []
				this.current = 1
				this.loadData()
			},
			change2(e) {
				// this.$refs.table.clearSelection()
				this.selected = []
				this.current = 1
				this.loadData()
			},
			// 重置
			toReLoad() {
				this.selected = []
				this.current = 1
				this.username = ''
				this.nickname = ''
				this.organization = []
				this.orgin_text = ''
				this.loadData()
			},
			// 分页触发
			// changePage(e) {
			// 	this.$refs.table.clearSelection()
			// 	this.selectedIndexs.length = 0
			// 	this.getData(e.current)
			// },
			// 加载数据的方法
			async loadData() {
				// 这里模拟从服务器获取数据，实际应用中应从服务器获取并处理分页逻辑
				const result = await adminLists({
					page: this.current,
					size: this.pageSize,
					username: this.username,
					nickname: this.nickname,
					organization: this.organization
				})

				if (result.code == 1) {
					this.total = result.data.total
					this.tableData = result.data.list
					let length = this.countCommonElements(this.tableData, this.selected)
					if (length == this.tableData.length) {
						this.checkAll = true
					} else {
						this.checkAll = false
					}
				} else {
					uni.showToast({
						title: result.msg,
						icon: 'error'
					})
				}
			},
			countCommonElements(arr1, arr2) {
				// 使用filter方法从arr1中筛选出存在于arr2中的元素
				const commonElements = arr1.filter(item => arr2.includes(item.id.toString()));
				// 返回共有元素的数量
				return commonElements.length;
			},
			// 分页改变时触发的方法
			handlePageChange(event) {
				// this.$refs.table.clearSelection()
				// this.selectedIndexs.length = 0
				this.current = event.current; // 更新当前页码
				this.loadData(); // 重新加载数据
				this.updateAllSelected()
			},
			handleChange(id) {
				let arr = this.selected
				this.selected = this.selected.concat([id])
				this.selected = this.removeDuplicates(this.selected)
				// this.selected = this.selected.filter(item => item !== id)
				// console.log(this.selected)
				this.updateAllSelected();
			},
			all_change() {
				this.checkAll = !this.checkAll;
				if (this.checkAll) {
					const arrS = this.selected.concat(this.tableData.map(item => item.id.toString()));
					this.selected = Array.from(new Set(arrS));
				} else {
					// this.selected = [];
					let array = this.selected;
					// 要删除的值列表
					let valuesToRemove = [];
					this.tableData.forEach(item => {
						valuesToRemove.push(item.id.toString())
					})
					valuesToRemove.forEach(value => {
						let index = array.indexOf(value);
						if (index > -1) {
							array.splice(index, 1);
						}
					});
					const uniqueArr = Array.from(new Set(array));
					this.selected = uniqueArr
				}
				// console.log(this.selected)
			},
			iselected(id) {
				return this.selected.includes(id.toString());
			},
			updateAllSelected() {
				this.checkAll = this.selected.length === this.tableData.length;
			},
			removeDuplicates(arr) {
				const countMap = arr.reduce((acc, val) => {
					acc[val] = (acc[val] || 0) + 1;
					return acc;
				}, {});

				return arr.filter(val => countMap[val] === 1);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uni-table {
		margin: 20rpx;
		background: white;
		padding: 0 30rpx 30rpx;
	}

	.sendBtn {
		background: #00aaff;
		color: white;
		font-size: 24rpx;
		padding: 18rpx 20rpx;
		border-radius: 8rpx;
	}

	.sendBtn2 {
		padding: 18rpx 16rpx;
		background: #55aaff;
	}

	.inputView {
		width: 100%;
		padding: 2rpx;
		font-size: 28rpx;
		margin-bottom: 20rpx;
		.textarea{
			margin-top: 10rpx;
			border: solid 1rpx gainsboro;
		}
	}

	.inputView2 {
		border: solid 1px #e5e5e5;
		font-size: 24rpx;
		padding: 10rpx 20rpx;

		input {
			width: 85%;
		}
	}
</style>